<script setup>
import personalCenterService from '@/services/personal-center.service';
import { useAuthStore } from '@/stores/auth';
import { AxiosError } from 'axios';
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import authService from '@/services/auth.service';
import { REGEX_PASSWORD } from "@/utils/regexes";
import { showFailToast, showNotify } from 'vant';
import TabbarWrapper from '@/components/TabbarWrapper.vue';

const router = useRouter();
const authStore = useAuthStore();
const entity = ref({});
const loading = ref(false);
const verifyCodeUrl = ref("");

const formRef = ref();
const rules = reactive({
    oldPassword: [
        {
            required: true,
            message: '请输入旧密码',
        },
    ],
    newPassword: [
        {
            required: true,
            message: '请输入新密码',
        },
        {
            validator: (value) => {
                return REGEX_PASSWORD.test(value);
            },
            message: "密码格式应为8-18位数字、字母、符号的任意两种组合",
        }
    ],
    confirmPassword: [
        {
            required: true,
            message: '请输入确认密码',
        },
        {
            validator: (value) => {
                return !(entity.value.newPassword && entity.value.confirmPassword && entity.value.newPassword != entity.value.confirmPassword);
            },
            message: "两次密码输入不一致",
        }
    ],
    verifyCode: [
        {
            required: true,
            message: '请输入验证码',
        },
    ],
});

const save = async () => {
    try {
        loading.value = true;
        await personalCenterService.changePassword(entity.value);
        authStore.unAuthenticate();
        router.push("/login");
        showNotify({
            message: "保存成功", type: "success"
        });
    } catch (err) {
        if (err instanceof AxiosError) {
            const msg = err.response?.data?.message || err.message;
            showFailToast({ message: msg, type: "error" });
        }
        throw err;
    } finally {
        loading.value = false;
    }
};

const updateVerifyCode = async () => {
    const res = await authService.getVerifyCode();
    verifyCodeUrl.value = `${res.data.data?.image}`;
    entity.value.verifyCodeKey = res.data.data?.key;
}

onMounted(() => {
    entity.value = {};
    updateVerifyCode();
});
</script>

<template>
    <div class="page-container absolute left-0 top-0 w-full h-full flex flex-col">
        <div class="header-container">
            <VanNavBar title="修改密码" left-arrow left-text="返回" @click-left="router.back()"></VanNavBar>
        </div>

        <div class="main-container flex-grow">
            <VanForm>
                <VanCellGroup inset>
                    <VanField v-model:model-value="entity.oldPassword" type="password" name="oldPassword" label="旧密码"
                        placeholder="旧密码" :rules="rules.oldPassword">
                    </VanField>
                    <VanField v-model:model-value="entity.newPassword" type="password" name="newPassword" label="新密码"
                        placeholder="密码" :rules="rules.newPassword">
                    </VanField>
                    <VanField v-model:model-value="entity.confirmPassword" type="password" name="confirmPassword"
                        label="确认密码" placeholder="确认密码" :rules="rules.confirmPassword">
                    </VanField>
                    <VanField class="" v-model:model-value="entity.verifyCode" name="verifyCode" label="验证码"
                        placeholder="验证码" :rules="rules.verifyCode">
                        <template #button>
                            <img :src="verifyCodeUrl" class="verify-code" @click="updateVerifyCode()" />
                        </template>
                    </VanField>
                </VanCellGroup>
                <VanCellGroup inset>
                    <VanButton round block type="primary" @click="save">
                        保存
                    </VanButton>
                </VanCellGroup>
            </VanForm>
        </div>

        <div class="footer-container">
            <TabbarWrapper active-tab="mine"></TabbarWrapper>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.verify-code {
    height: 40px;
}
</style>